package com.central.apps.handler.docassociatedquery;

import com.central.app.common.base.BaseHandler;
import com.central.app.service.HandlerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 单据联查业务逻辑
 *
 * @author lidachao
 * @date 2022/11/9
 */
@Component
@Slf4j
public class DocAssociatedQueryHandler extends BaseHandler {
    @Autowired
    private HandlerService handlerService;

    @Override
    public String validateSave(String app, String objName, Map<String, Object> data) throws Exception {
        if ("gq_docassociatedquerycfg".equals(objName)){
            Integer id = MapUtils.getInteger(data, "id");
            String daqcnum = MapUtils.getString(data, "daqcnum", "");

            if (null == id) {
                // 查询单据联查配置信息
                List<Map<String, Object>> daqcList = handlerService.findBySql("select daqcnum from gq_docassociatedquerycfg where daqcnum = '" + daqcnum + "'");
                if (CollectionUtils.isNotEmpty(daqcList)) {
                    return "单据联查配置编码重复, 请重新编写！";
                }
            }
        }
        return null;
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("gq_docassociatedquerycfg".equals(objName) && !isUpdate){
            Integer parentid = MapUtils.getInteger(data, "parentid", 0);

            if (parentid > 0) {
                Integer id = MapUtils.getInteger(data, "id", 0);
                // 查询单据联查配置信息
                List<Map<String, Object>> daqcList = handlerService.findBySql("select daqclevel from gq_docassociatedquerycfg where id = " + parentid);
                Map<String, Object> daqcMap = daqcList.get(0);
                Integer daqclevel = MapUtils.getInteger(daqcMap, "daqclevel");
                daqclevel = daqclevel + 1;

                // 更新单据联查配置信息
                handlerService.updateBySql("update gq_docassociatedquerycfg set daqclevel = " + daqclevel + " where id = " + id);
            }

        }
    }
}
